var o = require("Utils"),
    i = require("psconfig"),
    a = require("gameData");
cc.Class({
    extends: cc.Component,
    properties: {
        game: cc.Node,
        starRoot: cc.Node,
        starPrefab: cc.Prefab,
        starParticle: cc.Prefab,
        scorePrefab: cc.Prefab,
        progressBar: cc.ProgressBar,
        currScoreLabel: cc.Label,
        targetScore: cc.Label,
        selectColorLayer: cc.Node,
        waitingLayer: cc.Node,
        beginPos : cc.Label,
        touchPos : cc.Label,
        _currScore: 0,
        _targetScore: 0,
        _starPool: null,
        scoreList: [],
        particleList: [],
        _toolType: 0,
        _totalCounts: 0,
        _currCount: 0,
        _bombList: [],
        _tamping: !1
    },
    init: function () {
        console.log("地图初始化配置"), i.cellSize = this.starRoot.width / i.matrixRow - 2, this._starPool = new cc.NodePool();
        for (var t = 0; t < 50; t++) {
            var e = cc.instantiate(this.starPrefab);
            this._starPool.put(e);
        }
        this._toolType = 0, this.touch = !0, this.click();
    },
    onDestroy: function () {
        this._starPool.clear(), this.scoreList = [], this.particleList = [];
    },
    deleteSprites: function (t) {
        this._tamping || o.indexOfV2(this._bombList, t[0]) || (this._totalCounts += t.length,
            this._bombList = this._bombList.concat(t), a.cleanStarData(t), t.sort(function (t, e) {
                return t.y - e.y;
            }), this.removeSelectedStars(t, t.length));
    },
    removeSelectedStars: function (t, e) {
        var n = cc.callFunc(function () {
                if (this.waitingLayer.active = !0, t.length > 0) {
                    var n = t.shift(),
                        i = o.indexValue(n.x, n.y),
                        s = a.starSprite[i];
                    this.bombStar(s, i, e), a.starSprite[i] = null, ++this._currCount;
                } else this.updateMatrix();
            }, this),
            i = cc.sequence(n, cc.delayTime(.11)),
            s = cc.repeat(i, e + 1);
        this.node.runAction(s);
    },
    bombStar: function (t, e, n) {
        if (t) {
            this._starPool.put(t);
            var i = t.getComponent("Star")._starType;
            this.particleList[e].getComponent("StarParticle").play({
                position: t.getPosition(),
                type: i
            }), cc.director.emit("popSound");
            var a = this.node.convertToNodeSpaceAR(this.currScoreLabel.node.convertToWorldSpaceAR(cc.v2(0, 0)));
            this.scoreList[e].getComponent("Score").moveAnimation({
                fromP: t.getPosition(),
                toP: a,
                duration: .3,
                score: 5 * n,
                callback: function () {
                    var rate = 1;
                    if(n>10) rate = 10;
                    else if(n>8) rate = 8;
                    else if(n>5) rate = 5;
                    else if(n>2) rate = 2;
                    this._currScore += 5 * n * rate, this.currScoreLabel.string = this._currScore, this.progressBar.progress = o.getProgress(this._currScore, this._targetScore);
                }.bind(this)
            });
        }
    },
    updateMatrix: function () {
        if (this._totalCounts == this._currCount) {
            this._tamping = !0;
            var t = o.needCheckCols(this._bombList);
            this.tampRows(t), this.tampCols(t), this._tamping = !1, a.remainingStarCount -= this._totalCounts,
                this._totalCounts = 0, this._currCount = 0, this._bombList.splice(0, this._bombList.length);
        }
        this.scheduleOnce(function () {
            o.gameOver(a.starMatrix) && this.over(), this.waitingLayer.active = !1;
        }, .4);
    },
    tampRows: function (t) {
        t.forEach(function (t, e, n) {
            for (var s = 0, c = 0; c < i.matrixRow; c++)
                if (a.starMatrix[c][t] >= 0) {
                    if (s != c) {
                        e = o.indexValue(c, t);
                        var r = o.indexValue(s, t),
                            l = a.starSprite[e];
                        l.getComponent("Star").updateGrid(s, t), a.starSprite[r] = l, a.starSprite[e] = null,
                            a.starMatrix[s][t] = l.getComponent("Star")._starType, a.starMatrix[c][t] = -1;
                        var d = o.grid2Pos(s, t);
                        l.runAction(cc.moveTo(.13, d));
                    }
                    s++;
                }
        }, this);
    },
    tampCols: function (t) {
        t.forEach(function (t, e, n) {
            if (-1 == a.starMatrix[0][t]) {
                for (var s = !0, c = 1; c < i.matrixRow; c++)
                    if (a.starMatrix[c][t] >= 0) {
                        s = !1;
                        break;
                    }
                if (s && t < i.matrixCol - 1)
                    for (var r = t + 1; r < i.matrixCol; r++)
                        for (var l = 0; l < i.matrixRow && a.starMatrix[l][r] >= 0; l++) {
                            e = o.indexValue(l, r);
                            var d = a.starSprite[e];
                            d.getComponent("Star").updateGrid(l, r - 1), a.starSprite[e - 1] = d, a.starSprite[e] = null,
                                a.starMatrix[l][r - 1] = d.getComponent("Star")._starType, a.starMatrix[l][r] = -1,
                                d.runAction(cc.moveBy(.17, -(i.cellSize + 2), 0));
                        }
            }
        }, this);
    },
    deleteRemainAnimation: function () {
        console.log("消除剩余星星动画");
    },
    convertGridPositionToWorldSpaceAR: function (t) {
        var e = o.grid2Pos(t.x, t.y);
        return this.node.convertToWorldSpaceAR(e);
    },
    clearStarSprite: function () {
        if (a.starSprite) {
            a.starMatrix = null, this.scoreList = [], this.particleList = [];
            for (var t = a.starSprite.length, e = 0; e < t; e++) a.starSprite[e] && (a.starSprite[e].active = !1);
            a.starSprite.splice(0, t);
        }
    },
    countScore: function (t) {
        return t * t * 5;
    },
    createStar: function (t, e, n) {
        var o = null;
        return o = this._starPool.size() > 0 ? this._starPool.get() : cc.instantiate(this.starPrefab),
            this.node.addChild(o), o.getComponent("Star").initW(i.cellSize + 2), o.getComponent("Star").initStar(t, e, n),
            o;
    },
    initMatrix: function () {
        for (var t = 0; t < 10; t++)
            for (var e = a.starMatrix[t], n = 0; n < 10; n++) {
                var s = e[n],   // color
                    c = o.indexValue(t, n);
                if (s >= 0) {
                    var r = this.createStar(s, t, n);
                    a.starSprite[c] = r;
                } else a.starSprite[c] = null;
            }
        for (var l = 0; l < i.matrixCol * i.matrixRow; l++) {
            var d = cc.instantiate(this.scorePrefab);
            d.parent = this.node, d.active = !1, this.scoreList.push(d);
            var h = cc.instantiate(this.starParticle);
            h.parent = this.node, this.particleList.push(h);
        }
    },
    gameStart: function (t, e) {
        if (this._currScore = t, this._targetScore = e, 0 != a.starSprite.length) this.initMatrix(),
            this.starShowAnimation();
        else {
            var n = i.matrixRow * i.matrixCol;
            // 随机生成星星颜色
            a.remainingStarCount = n, a.starMatrix = o.initMatrixDataPortraitRandom(), this.initMatrix(),
                o.gameOver(a.starMatrix) ? this.initMatrix() : this.starShowAnimation();
        }
    },
    starShowAnimation: function () {
        //星星掉落动画
        var t = cc.callFunc(function () {
                this.waitingLayer.active = !0;
                for (var t = 0; t < 10; t++)
                    for (var e = 0; e < 10; e++) {
                        var n = o.indexValue(t, e);
                        a.starSprite[n] && (a.starSprite[n].active = !0, a.starSprite[n].getComponent("Star").goIntoDrop({
                            pos: cc.v2(37 + 74 * e, 37 + 74 * t + Math.floor(800 * Math.random()) % 800),
                            delay: .05 + Math.floor(10 * Math.random()) % 5 / 100
                        }));
                    }
            }, this),
            e = cc.callFunc(function () {
                this.waitingLayer.active = !1;
            }, this),
            n = cc.sequence(t, cc.delayTime(.5), e);
        this.node.runAction(n);
    },
    over: function () {
        var t = cc.callFunc(function () {
                console.log("over"), this.clearStarSprite(), this.particleList = [], console.log("分数：" + this._currScore),
                    console.log("奖励分数:" + a.getRewardScore(a.remainingStarCount)), this._currScore += a.getRewardScore(a.remainingStarCount),
                    this.currScoreLabel.string = this._currScore, this.progressBar.progress = o.getProgress(this._currScore, this._targetScore),
                    this.waitingLayer.active = !1, a.currScore = this._currScore, this._currScore >= this._targetScore ? (this.game.getComponent("Game").next(this._currScore),
                        cc.director.emit("winSound")) : (this.game.getComponent("Game").over(this._currScore),
                        cc.director.emit("failSound"));
            }, this),
            e = cc.sequence(cc.delayTime(1), t);
        return this.node.runAction(e), e;
    },
    blastOne: function (t) {
        console.log("使用锤子"), this.deleteSprites([t]), cc.director.emit("tool1Sound"),
            this.removeTool();
    },
    changeColor: function (t, e, n) {
        // n : 星星精灵
        console.log("选中刷子使用对象");
        var o = this;
        this.cancelSelected(), n.getComponent("Star").selected.node.active = !0, this.selectColorLayer.active = !0,
            this.selectColorLayer.getComponent("SelectColorLayer").init({
                pos: cc.v2(0, e.y + this.starRoot.position.y + 120),
                item: n,
                callback: function (e) {
                    console.log("使用刷子"), a.starMatrix[t.x][t.y] = e, n.getComponent("Star").changeStarType(e),
                        n.getComponent("Star").selected.node.active = !1, o.selectColorLayer.active = !1,
                        cc.director.emit("tool2Sound"), o.removeTool();
                }
            });
    },
    retryColor: function () {
        console.log("重置"), this.waitingLayer.active = !0, cc.director.emit("tool3Sound");
        for (var t = 0; t < i.matrixRow; t++)
            for (var e = 0; e < i.matrixCol; e++)
                if (a.starMatrix[t][e] >= 0) {
                    var n = Math.floor(10 * Math.random() % 5);
                    a.starMatrix[t][e] = n;
                }
        if (o.gameOver(a.starMatrix)) this.retryColor();
        else {
            for (t = 0; t < i.matrixRow; t++)
                for (e = 0; e < i.matrixCol; e++)
                    if (a.starMatrix[t][e] >= 0) {
                        var s = o.indexValue(t, e);
                        a.starSprite[s].getComponent("Star").fromSmallToBigAction({
                            type: a.starMatrix[t][e],
                            delay: .05 + Math.floor(10 * Math.random()) % 5 / 100
                        });
                    }
            this.scheduleOnce(function () {
                this.waitingLayer.active = !1;
            }, .7);
        }
    },
    setToolType: function (t) {
        3 == t.key ? (this.retryColor(), t.callback()) : (this._toolType = t.key, this.toolCallback = t.callback);
    },
    removeTool: function () {
        console.log("remove tool"), this.toolCallback(), this._toolType = 0;
    },
    cancelSelected: function () {
        a.starSprite && a.starSprite.forEach(function (t) {
            t && (t.getComponent("Star").selected.node.active = !1);
        });
    },
    click: function () {
        var t = this;
        this.node.on(cc.Node.EventType.TOUCH_START, function (e) {
            var n = e.getTouches();
            var o = n[0].getLocation();
            console.log(n);
            // console.log("begin pos : ", o.x,o.y);

            // // 屏幕分辨率 和 设计分辨率的适配坐标
            // // 当前屏幕分辨率
            // var screenWidth = cc.winSize.width;
            // var screenHeight = cc.winSize.height;
            // console.log("屏幕分辨率：",screenWidth,screenHeight);
            // //t.beginPos.string = "屏幕分辨率：(" + screenWidth + "," + screenHeight + ")"

            // // 设计分辨率
            // var designWidth = cc.Canvas.instance.designResolution.width;
            // var designHeight = cc.Canvas.instance.designResolution.height;
            // console.log("设计分辨率：",designWidth,designHeight);

            // // 计算缩放比例
            // var scaleX = screenWidth / designWidth;
            // var scaleY = screenHeight / designHeight;

            // // 转换触摸坐标到设计分辨率的坐标
            // o.x = o.x / scaleX;
            // o.y = o.y / scaleY;

            // console.log(o);

            // t.touchPos.string = "touch pos : (" + o.x + "," + o.y + ")";

            if (t.touch) {
                t.touch = !1;
                var nodePos = t.node.convertToNodeSpaceAR(o);
                nodePos.y -= 150;
                //t.beginPos.string = "begin pos : (" + nodePos.x + "," + nodePos.y + ")";
                t.gameModel(nodePos);
            }
        }, this.node), this.node.on(cc.Node.EventType.TOUCH_END, function (e) {
            t.touch = !0;
        }, this.node), this.node.on(cc.Node.EventType.TOUCH_CANCEL, function (e) {
            t.touch = !0;
        }, this.node);
    },
    removeStarModel : function(n,e){
        var c = o.removeStarsList(a.starSprite, a.starMatrix, e);
        // 神秘宝箱
        if(n.getComponent("Star")._starType == i.totalColors[5]){
            this.game.getComponent("Game").addGold(10*c.length);
            this.deleteSprites(c);
        }
        else
        {
            c.length >= 2 && this.deleteSprites(c);
        }
    },
    gameModel: function (t) {
        var e = o.pos2Grid(t.x, t.y);
        if (e.x < i.matrixRow && e.y < i.matrixCol) {
            var n = o.indexValue(e.x, e.y),
                s = a.starSprite[n];
            if (s) switch (this._toolType) {
                case 0:
                    this.removeStarModel(s,e)
                    // var c = o.removeStarsList(a.starSprite, a.starMatrix, e);
                    // c.length >= 2 && this.deleteSprites(c);
                    break;

                case 1:
                    this.blastOne(e);
                    break;

                case 2:
                    this.changeColor(e, t, s);
            }
        }
    }
})